<!--
 * @Descripttion:
 * @version:
 * @Author: xiajunchen
 * @Date: 2021-05-28 10:19:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-05-31 19:42:52
-->
<template>
  <div class="search-panel">
    <div class="search-items-warp">
      <template v-for="item in this.$props.list">
        <div :key="item.key" class="search-item">
          {{ item.label }}: <component :is="item.type" :items="item" />
        </div>
      </template>
    </div>
    <el-button
      v-if="showButton"
      type="primary"
      class="el-button-search"
      @click="handleSearch"
    >{{ this.$props.buttonTxt }}</el-button>
  </div>
</template>
<script>
import Select from './components/select'
import TimeRange from './components/timeRange'
import Input from './components/input'
export default {
  name: 'SearchPanel',
  components: {
    Select,
    TimeRange,
    Input
  },
  props: {
    showButton: {
      type: Boolean,
      default: true
    },
    buttonTxt: {
      type: String,
      default: '查找'
    },
    immediate: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array,
      default: () => ([])
    }
  },
  data: () => ({ params: {}}),
  mounted() { this.setDefaultValue() },
  methods: {
    setDefaultValue() {
      const arr = this.$props.list
      for (let i = arr.length - 1; i >= 0; i--) {
        this.gatherParams(arr[i], true)
      }
      this.$props.immediate && this.handleSearch()
    },
    gatherParams(obj, initImmediate) {
      if (obj.type.includes('Rang')) {
        if (obj.key) { // 后端不是分开接受时间，是合在一起的，有key 的优先高
          if (obj.value[0] && obj.value[1]) { // 判断 2个时间值是不是都存在
            this.params[obj.key] = `${obj.value[0]},${obj.value[1]}`
          } else {
            this.params[obj.key] = undefined // 只要一个不存在直接赋值 undefined
          }
        } else { // 后端分开接受时间
          if (obj.value) {
            this.params[obj.startkey] = obj.value[0]
            this.params[obj.endkey] = obj.value[1]
          } else {
            this.params[obj.startkey] = undefined
            this.params[obj.endkey] = undefined
          }
        }
      } else {
        this.params[obj.key] = obj.value
      }
      if (initImmediate) return
      this.$props.immediate && this.handleSearch()
    },
    handleSearch() {
      this.$emit('onSerach', { ...this.params })
    }
  }
}
</script>
<style lang="scss" scoped>
.search-panel {
  display: flex;
  .search-items-warp {
    flex: 1;
    .search-item {
    display: inline-block;
    margin-right: 20px;
    }
  }
  .el-button-search {
    align-items: center;
    height: 40px;
  }
}
</style>
